<?php

namespace Iut\omgl6Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Iut\omgl6Bundle\Entity\BilletIncident;
use Iut\omgl6Bundle\Form\BilletIncidentType;
use Iut\omgl6Bundle\Entity\Affectation;

/**
 * BilletIncident controller.
 *
 */
class BilletIncidentController extends Controller
{
    /**
     * Lists all BilletIncident entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entities = $em->getRepository('Iutomgl6Bundle:BilletIncident')->findAll();

        return $this->render('Iutomgl6Bundle:BilletIncident:index.html.twig', array(
            'entities' => $entities
        ));
    }

    /**
     * Finds and displays a BilletIncident entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('Iutomgl6Bundle:BilletIncident')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find BilletIncident entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('Iutomgl6Bundle:BilletIncident:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),

        ));
    }

    /**
     * Displays a form to create a new BilletIncident entity.
     *
     */
    public function newAction()
    {
        $entity = new BilletIncident();
        $form   = $this->createForm(new BilletIncidentType(), $entity);

        return $this->render('Iutomgl6Bundle:BilletIncident:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));
    }

    /**
     * Creates a new BilletIncident entity.
     *
     */
    public function createAction()
    {
		$date = new \DateTime("now");
        $entity  = new BilletIncident();
        $request = $this->getRequest();
        $form    = $this->createForm(new BilletIncidentType(), $entity);
        $form->bindRequest($request);
		$entity->setDateFinPrevue($date);
		$entity->setDateFinPrevue($date);
		
		
		$ProblemeLogiciel = $entity->getIdProblemeLogiciel();
		$ProblemeMateriel = $entity->getIdProblemeMateriel();
		
		$em = $this->getDoctrine()->getEntityManager();
		
		//Dans le cas ou c'est un probleme logiciel, dans le cas inverse l'utilisateur choisit "..." dans la combo box et l'id renvoy� est 1.
		if ($ProblemeLogiciel != null)
		{
			$operateurMoinsCharge = $this->findOperateurLogiciel($ProblemeLogiciel);
		}
                
		if ($ProblemeMateriel != null)
		{
			$operateurMoinsCharge = $this->findOperateurMateriel($ProblemeMateriel);
		}
		
		$affectation = new Affectation();
		$affectation -> setDatePriseEnCharge($date);
		$affectation -> setIdBilletIncident($entity);
		$affectation -> setIdPersonnelTechnique($operateurMoinsCharge);
		$em->persist($affectation);
		$em->persist($affectation->getIdPersonnelTechnique());
		$em->persist($affectation->getIdBilletIncident());
		$em->flush();
			

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
			// $entity->setIdEmetteur(1);
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('billetincident_show', array('id' => $entity->getId())));
            
        }

        return $this->render('Iutomgl6Bundle:BilletIncident:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));
    }
	
	public function findOperateurLogiciel($ProblemeLogiciel){
	$countMin = 100;
	$operateurMoinsCharge = null;
	$em = $this->getDoctrine()->getEntityManager();
	$tabOperateur = $em->getRepository('Iutomgl6Bundle:PersonnelTechnique')->findAll();
	$tabAffection = $em->getRepository('Iutomgl6Bundle:Affectation')->findAll();
	$tabOperateurHabilite = Array();
		foreach ( $tabOperateur as $operateur){
		$count = 101;
			foreach ($operateur->getIdProblemeLogiciel() as $competence){
				if ($competence->getLibelleProblemeLogiciel() == $ProblemeLogiciel->getLibelleProblemeLogiciel()){
					$count = 0;
					if ($tabAffection == null){
						$count = 0;
					} else {
						foreach ($tabAffection as $affectation1){
							if ($affectation1->getIdPersonnelTechnique()->getId() == $operateur->getId() ){
								$count++;
							}
						}
					}
					if ( $count < $countMin ){
						$operateurMoinsCharge = $operateur;
						$countMin = $count;
					}
				}
				
			}
		}
		if ($operateurMoinsCharge != null){
			return $operateurMoinsCharge;
		}
		else {
			return $operateurMoinsCharge = $em->getRepository('Iutomgl6Bundle:PersonnelTechnique')->find(6);
		}
	}
	
	public function findOperateurMateriel($ProblemeMateriel){
	$countMin = 100;
	$operateurMoinsCharge = null;
	$em = $this->getDoctrine()->getEntityManager();
	$tabOperateur = $em->getRepository('Iutomgl6Bundle:PersonnelTechnique')->findAll();
	$tabAffection = $em->getRepository('Iutomgl6Bundle:Affectation')->findAll();
	$tabOperateurHabilite = Array();
		foreach ( $tabOperateur as $operateur){
		$count = 101;
			foreach ($operateur->getIdProblemeMateriel() as $competence){
				if ($competence->getLibelleProblemeMateriel() == $ProblemeMateriel->getLibelleProblemeMateriel()){
					$count = 0;
					if ($tabAffection == null){
						$count = 0;
					} else {
						foreach ($tabAffection as $affectation1){
							if ($affectation1->getIdPersonnelTechnique()->getId() == $operateur->getId() ){
								$count++;
							}
						}
					}
					if ( $count < $countMin ){
						$operateurMoinsCharge = $operateur;
						$countMin = $count;
					}
				}
				
			}
		}
		if ($operateurMoinsCharge != null){
			return $operateurMoinsCharge;
		}
		else {
			return $operateurMoinsCharge = $em->getRepository('Iutomgl6Bundle:PersonnelTechnique')->find(6);
		}
	}

    /**
     * Displays a form to edit an existing BilletIncident entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('Iutomgl6Bundle:BilletIncident')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find BilletIncident entity.');
        }

        $editForm = $this->createForm(new BilletIncidentType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('Iutomgl6Bundle:BilletIncident:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Edits an existing BilletIncident entity.
     *
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('Iutomgl6Bundle:BilletIncident')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find BilletIncident entity.');
        }

        $editForm   = $this->createForm(new BilletIncidentType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('billetincident_edit', array('id' => $id)));
        }

        return $this->render('Iutomgl6Bundle:BilletIncident:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a BilletIncident entity.
     *
     */
    public function deleteAction($id)
    {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('Iutomgl6Bundle:BilletIncident')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find BilletIncident entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('billetincident'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
    
    private function indexAffectationAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        
        $user = $this->container->get('security.context')->getToken()->getUser();
        $user->getUsername();
        
        $query = $em->createQuery("SELECT a FROM Iutomgl6Bundle:Affectation a");
            $affect = $query->getResult();
        
        $query = $em->createQuery("SELECT b FROM Iutomgl6Bundle:BilletIncident b JOIN WHERE ");
            $query->setParameter('user', $user);
            $query->setParameter('affect', $affect);
            $entities = $query->getSingleScalarResult();
    }
}
